# -*- coding: utf-8 -*-

import json
import logging
import datetime

from django.utils.encoding import smart_unicode
from django.views.decorators.http import require_POST
from django.views.generic import TemplateView
from django.utils.decorators import method_decorator

from common.lottery import db
from common.utils.decorator import response_wrapper
from common.utils.api import token_required, check_params
from common.utils.tz import utc_to_local_str
from common.lottery.cyclical.abstract.order import get_order
from common.lottery.cyclical import ORDER_STATUS
from common.utils.exceptions import ParamError
from common.utils import tz
import logging

_LOGGER = logging.getLogger(__name__)


class OrderView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        if 'created_at' not in query_dct and 'user_id' not in query_dct and 'order_id' not in query_dct:
            today = tz.local_now().strftime('%Y-%m-%d')
            query_dct['created_at'] = '{"$gte":"' + today + \
                                      ' 00:00:00","$lt":"' + today + ' 23:59:59"}'
        elif 'user_id' not in query_dct and 'order_id' not in query_dct:
            created_at = eval(query_dct['created_at'])
            start_date = datetime.datetime.strptime(created_at['$gte'][0:10], "%Y-%m-%d")
            end_date = datetime.datetime.strptime(created_at['$lt'][0:10], "%Y-%m-%d")
            if 7 < (end_date - start_date).days:
                raise ParamError(u'时间区间大于7天')
        # user_id = query_dct.get('user_id')
        # if user_id is None:
        #     return {}
        if 'bet_type' in query_dct:
            query_dct["detail"] = json.dumps({"$like": '%bet_type": ' + str(query_dct["bet_type"]) + '%'})
        # if not query_dict.get('user_id'):
        #    query_dict['ｓstatus'] = query_dict.get('status') or str(ORDER_STATUS.UNCHECK)
        items, total_count = db.list_all_orders(query_dct)

        resp = []
        for item in items:
            data = item.as_dict()
            data['created_at'] = utc_to_local_str(item.created_at)
            order_detail = get_order(data['activity_type'], data['user_id'], data['order_id'])
            data['detail'] = order_detail.as_dict()
            data['detail']['number'] = data['detail']['number'].replace('|', '| ')
            data['detail']['created_at'] = utc_to_local_str(data['detail']['created_at'])
            data['detail']['updated_at'] = utc_to_local_str(data['detail']['updated_at'])
            resp.append(data)

        return {'list': resp, 'page': query_dct.get('$page', 1),
                'total_count': total_count, 'size': len(resp)}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(OrderView, self).dispatch(*args, **kwargs)


@require_POST
@response_wrapper
@token_required
def approve_order(req, order_id, status):
    status = int(status)
    order_id = long(order_id)
    db.check_order({'id': order_id, 'status': status})
    return {}
